package controllers

import (
	"context"
	"fiber-layout/app/constant"
	"fiber-layout/app/exceptions"
	"fiber-layout/app/requests"
	"fiber-layout/app/services"
	"fiber-layout/provider/logger"
	"github.com/gofiber/fiber/v2"
	"github.com/gogf/gf/v2/util/gvalid"
)

// UserRegister 用户注册
func UserRegister() fiber.Handler {
	return func(c *fiber.Ctx) error {
		//将请求绑定到结构
		u := &requests.RegisterRequest{}
		err := c.BodyParser(u)
		if err != nil {
			logger.Log.Error(constant.ErrRequest.Error() + err.Error())
			return exceptions.Response(c, nil, constant.ErrRequest.Error(), 4000)
		}
		//数据验证
		validator := gvalid.New()
		if err := validator.Data(u).Run(context.Background()); err != nil {
			return exceptions.Response(c, nil, err.String(), 4000)
		}
		//services
		return services.RegisterService(u, c)
	}
}

// UserLogin 用户登录
func UserLogin() fiber.Handler {
	return func(c *fiber.Ctx) error {
		//将请求绑定到结构
		u := &requests.LoginRequest{}
		err := c.BodyParser(u)
		if err != nil {
			logger.Log.Error(constant.ErrRequest.Error() + err.Error())
			return exceptions.Response(c, nil, constant.ErrRequest.Error(), 4000)
		}
		//数据验证
		validator := gvalid.New()
		if err := validator.Data(u).Run(context.Background()); err != nil {
			return exceptions.Response(c, nil, err.String(), 4000)
		}
		//services
		return services.LoginService(u, c)
	}
}

// UserDelete 用户删除
func UserDelete() fiber.Handler {
	return func(c *fiber.Ctx) error {
		//将请求绑定到结构
		u := &requests.DeleteRequest{}
		id, err := c.ParamsInt("id")
		if err != nil {
			logger.Log.Error(constant.ErrRequest.Error() + err.Error())
			return exceptions.Response(c, nil, constant.ErrRequest.Error(), 4000)
		}
		u.ID = uint(id)
		//数据验证
		validator := gvalid.New()
		if err := validator.Data(u).Run(context.Background()); err != nil {
			return exceptions.Response(c, nil, err.String(), 4000)
		}
		//services
		return services.DeleteService(u.ID, c)
	}
}
